import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_learning/download/views/ly_file_list_view.dart';
import 'package:flutter_learning/isolate/utils/ly_log.dart';
import 'package:flutter_learning/memo_s3/controller_widget.dart';
import 'package:flutter_learning/page_lifecycle/base_page_lifecycle_state.dart';
import 'package:flutter_learning/page_lifecycle/lifecycle_home_view.dart';
import 'package:flutter_learning/polar/polar_manager.dart';
import 'package:flutter_learning/routes/app_pages.dart';
import 'package:flutter_learning/widgets/ly_draw_arrow_view.dart';
import 'package:flutter_learning/widgets/ly_index_list_view.dart';
import 'package:get/get.dart';
import 'package:sliding_motion/ly_sliding_motion_control.dart';
import 'isolate/ly_isolate_balancer.dart';
import 'ly_home_view.dart';
import 'network/base_response.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initializeLoadBalancer();
  runApp(const MyApp());
  // LYIsolateNetworkManager.ordersList("accessToken", "deviceId");
  // final res = await LYIsolateManager.lb.run(requestData, {"deviceId": '123'});
  // LYLog.d(res);
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.

  String? result;
  @override
  void initState() {
    super.initState();
    // final polarManager = PolarManager();
    // start();
  }

  void start() async {
    // LYIsolateManager.test();LYIsolateManager
    performSelector(requestData, {"deviceId": "1233455"}).then((onValue) {
      LYLog.d("onValue=$onValue");
    });
  }

  static Future<String> requestData(Map parameters) async {
    final deviceId = parameters['deviceId'];
    LYLog.d("parameters=$parameters");
    Dio api = Dio();
    api.options.contentType = 'application/json';
    api.options.connectTimeout = const Duration(seconds: 30);
    api.options.receiveTimeout = const Duration(seconds: 30);
    api.options.headers = {
      "Content-Type": "application/json",
      "product": "reception",
      "device_id": deviceId,
      "ticket": deviceId,
      // "access_token": accessToken,
    };
    // 日志拦截器
    // api.interceptors.add(the_dio.LogInterceptor(responseBody: true));
    final res = await api.post("https://api.ymlinks.com/user/admin/login",
        data: {"username": "test", "password": "666888"});
    final baseResponse = BaseResponse(
      code: BaseResponseCode.success,
      msg: '数据请求成功啦!',
      success: true,
      result: res.data['result'],
    );
    return res.data.toString();
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: '测试',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      // home: LifecycleHomeView(),
      navigatorObservers: [routeObserver],
      getPages: AppPages.routes,
      initialRoute: AppPages.home,
      // home: ControllerWidget(),
      // home: LYIndexListView(),
      // home: Column(
      //   children: [
      //     Container(
      //       child: Text(
      //         result ?? '',
      //         maxLines: 1000,
      //       ),
      //     ),
      //     LYSlidingMotionControl(
      //       boundsSize: 200,
      //     ),
      //   ],
      // ),
      // home: const DirectionArrowPage(),
      builder: EasyLoading.init(),
    );
  }
}

class CustomAnimationExample extends StatefulWidget {
  const CustomAnimationExample({super.key});

  @override
  _CustomAnimationExampleState createState() => _CustomAnimationExampleState();
}

class _CustomAnimationExampleState extends State<CustomAnimationExample>
    with SingleTickerProviderStateMixin {
  bool _isOn = false;
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: Duration(seconds: 1));
    _animation = Tween<double>(begin: 0.0, end: 1.0)
        .animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Animation Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedBuilder(
              animation: _animation,
              builder: (context, child) {
                return Transform.scale(
                  scale: _animation.value,
                  child: Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      color: _isOn ? Colors.green : Colors.red,
                      shape: BoxShape.circle,
                    ),
                    child: Center(child: Text(_isOn ? 'On' : 'Off')),
                  ),
                );
              },
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isOn = !_isOn;
                  if (_isOn) {
                    _controller.forward();
                  } else {
                    _controller.reverse();
                  }
                });
              },
              child: Text(_isOn ? 'Turn Off' : 'Turn On'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class TweenAnimationBuilderExample extends StatefulWidget {
  @override
  _TweenAnimationBuilderExampleState createState() => _TweenAnimationBuilderExampleState();
}

class _TweenAnimationBuilderExampleState extends State<TweenAnimationBuilderExample> {
  bool _isOn = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TweenAnimationBuilder Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TweenAnimationBuilder(
              tween: ColorTween(begin: Colors.red, end: Colors.green),
              duration: Duration(seconds: 1),
              builder: (context, color, child) {
                return Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    color: color,
                    shape: BoxShape.circle,
                  ),
                  child: Center(child: Text(_isOn ? 'On' : 'Off')),
                );
              },
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isOn = !_isOn;
                });
              },
              child: Text(_isOn ? 'Turn Off' : 'Turn On'),
            ),
          ],
        ),
      ),
    );
  }
}
